#include "filePipe.h"

filePipe::filePipe():   file(NULL){}
filePipe::~filePipe(){}

inputFilePipe::inputFilePipe(){}
inputFilePipe::~inputFilePipe(){}

unsigned long inputFilePipe::rAvail(){
    long pos = ftell( file );
    fseek(file,0,SEEK_END);
    unsigned long size = pos - ftell(file);
    fseek(file,pos,SEEK_SET);
    return size;
}
bool inputFilePipe::isRAvail(){
    return !feof(file);
}

dSStatus inputFilePipe::consumeIS(){
    if( !file || !outStream ) return dSt_nullStream;
    unsigned char buffer[DFT_CHUNK_SIZE];
    unsigned int size;
    while( !feof( file ) ){
        size = fread( buffer, 1, DFT_CHUNK_SIZE, file );
        outStream->write(buffer,size);
    }
    return dSt_ok;
}
dSStatus inputFilePipe::seqConsumeIS(){
    if( !file || !outStream ) return dSt_nullStream;
    unsigned char buffer[DFT_CHUNK_SIZE];
    unsigned int size;
    size = fread( buffer, 1, DFT_CHUNK_SIZE, file );
    outStream->write(buffer,size);
    return dSt_ok;
}
dSStatus inputFilePipe::operateIS(unsigned int size){
    if( !file || !outStream ) return dSt_nullStream;
    unsigned char* buffer = new unsigned char[size];
    unsigned int size2 = fread( buffer, 1, size, file );
    outStream->write(buffer,size2);
    if( size2 < size ) return dSt_notEnData;
    delete buffer;
    return dSt_ok;
}

outputFilePipe::outputFilePipe(){}
outputFilePipe::~outputFilePipe(){}

dSStatus outputFilePipe::consumeIS(){
    if( !file || !inStream ) return dSt_nullStream;
    if( !inStream->rAvail() ) return dSt_noData;
    unsigned char buffer[DFT_CHUNK_SIZE];
    unsigned int size;
    while( (size = inStream->rAvail()) ){
        if( size > DFT_CHUNK_SIZE ) size = DFT_CHUNK_SIZE;
        unsigned int size2 = size;
        inStream->read(buffer,&size);
        fwrite(buffer, 1, size2 - size, file);
    }
    fflush(file);
    return dSt_ok;
}
dSStatus outputFilePipe::seqConsumeIS(){
    if( !file || !inStream ) return dSt_nullStream;
    unsigned char buffer[DFT_CHUNK_SIZE];
    unsigned int size = DFT_CHUNK_SIZE;
    unsigned int size2 = size;
    inStream->read(buffer,&size);
    fwrite(buffer, 1, size2 - size, file);
    fflush(file);
    return dSt_ok;
}
dSStatus outputFilePipe::operateIS(unsigned int size){
    if( !file || !inStream ) return dSt_nullStream;
    if( !inStream->rAvail() ) return dSt_noData;
    unsigned char* buffer = new unsigned char[size];
    unsigned int size2 = size;
    inStream->read(buffer,&size);
    fwrite(buffer, 1, size2-size, file);
    if( size ) return dSt_notEnData;
    fflush(file);
    delete buffer;
    return dSt_ok;
}
